
package com.mt.common.core.utils;

import com.alibaba.fastjson.JSONObject;
import com.mt.common.core.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 *
 *
 * @author zhanghong
 * @date 2023-03-14 9:52
 */
@Component
public class WxUtil {
    @Autowired
    private RestTemplate restTemplate;
    public String getOpenId(String code){
        String url="https://api.weixin.qq.com/sns/jscode2session?" +
                "appid="+ Config.APPID +
                "&secret="+Config.APPSECRET +
                "&js_code="+code +
                "&grant_type=authorization_code";
        String jsonData = restTemplate.getForObject(url, String.class);
        System.out.println("**jsonData**:"+jsonData); //打印jsonData
        JSONObject jsonObject= JSONObject.parseObject(jsonData);
        return jsonObject.get("openid") == null ? "" : String.valueOf(jsonObject.get("openid")).trim();
    }

    public String getAccessToken(){
        String url="https://api.weixin.qq.com/cgi-bin/token?"+"grant_type=client_credential&appid="+Config.APPID+"&secret="+Config.APPSECRET;
        String json = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(json);
        return (String) jsonObject.get("access_token");
    }


    public String sendMessage(String jsonString){
        String url="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+getAccessToken();
        HttpHeaders headers=new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonString, headers);
        return restTemplate.postForObject(url, httpEntity, String.class);
    }
}
